import 'package:buy_flutter/common/Application.dart';
import 'package:buy_flutter/common/sp/UserSharePreference.dart';
import 'package:buy_flutter/net/net_config.dart';
import 'package:buy_flutter/page/main/view/main_view.dart';
import 'package:buy_flutter/page/splash/bloc/application_bloc.dart';
import 'package:buy_flutter/page/splash/view/welcome_page.dart';
import 'package:buy_flutter/router/routes.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class SplashPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    Routes.configRoutes(Application.router);
    return _SplashState();
  }
}

class _SplashState extends State {
  ApplicationBloc _applicationBloc = ApplicationBloc();

  @override
  void initState() {
    try {
      print("_SplashState,initState====>");
      UserSharePreference.getJwt().then((value) {
        print("_SplashState,getJwt().then,jwt====>" + value);
        int status = (value == null || value.length == 0) ? 1 : 2;
        NetConfig.jwt=value;
        _applicationBloc.add(new InitApplicationEvent(status));

      }).onError((error, stackTrace) {
        print("onError,Exception====>");
        _applicationBloc.add(new InitApplicationEvent(1));
      });
    } on Exception catch (e) {
      print("Exception====>");
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<ApplicationBloc>(
      create: (context) {
        return _applicationBloc;
      },
      child: BlocBuilder<ApplicationBloc, ApplicationState>(
        builder: (context, state) {
          if (state == null) {
            return _mainWidget(0);
          }
          return _mainWidget(state.initStatus);
        },
      ),
    );
  }

  Widget _mainWidget(int initStatus) {
    return MaterialApp(
      home: (initStatus == 0)
          ? Center(child: Image.asset("assets/login/logo.png"))
          : ((initStatus == 1) ? WelcomePage() : MainView()),
    );
  }
}
